import { defineStore } from 'pinia'
import { api } from '../services/api'
import type { Message } from '../types'
import { ElMessage } from 'element-plus'

interface ChatContent {
  content: string
  contentType: string
}

interface ChatRequest {
  appId: number
  userId: number
  contents: ChatContent[]
  knowledgeIds: string[]
  isStream: number
}

export const useChatStore = defineStore('chat', {
  state: () => ({
    messages: [] as Message[],
    isLoading: false,
    error: null as string | null,
    formData: {} as Record<string, any>,
    formDataIsShow: false,
    questionSuggestions: [ // 新增的默认值
      // "您需要更多信息吗？",
      // "还有其他问题需要解答吗？",
      // "我可以帮您查询其他相关内容吗？",
      // "您对当前问题的解决方案满意吗？"
    ] as string[],
  }),

  actions: {
    async sendMessage(chatRequest: ChatRequest) {
      console.log("1111111", chatRequest);

      if (chatRequest.isStream === 1) {

        try {
          this.isLoading = true

          // 创建用户消息
          const userContent = chatRequest.contents
            .map(content => content.content)
            .join('\n')

          const newMessage: Message = {
            id: Date.now().toString(),
            content: userContent,
            role: 'user',
            timestamp: Date.now()
          }
          this.messages.push(newMessage)

          let aiResponse = ''
          let res = null;
          await api.sendMessage(chatRequest, (text, toolRes) => {
            aiResponse = text
            res = toolRes;

            console.log(res);
            console.log(toolRes);

            const lastMessage = this.messages[this.messages.length - 1]
            if (lastMessage.role === 'assistant') {
              lastMessage.content = aiResponse
            } else {
              this.messages.push({
                id: (Date.now() + 1).toString(),
                content: aiResponse,
                role: 'assistant',
                timestamp: Date.now()
              })
            }
          })
        } catch (err) {
          const errorMessage = err instanceof Error ? err.message : '发送消息失败'
          this.error = errorMessage
          ElMessage.error(errorMessage)
        } finally {
          // console.log("响应完成接着发请求获取用户可能的提问");
          // const response = api.sendMessage4({
          //   appId: "1889570169345757186",
          //   userId: 33,
          //   contents: chatRequest.contents,
          //   knowledgeIds: [],
          //   // 直接传递 1, 2, 或 3
          // })
          // console.log(response);

          this.isLoading = false
        }
      } else if (chatRequest.isStream === 2) {
        try {
          this.isLoading = true

          // 创建用户消息
          const userContent = chatRequest.contents
            .map(content => content.content)
            .join('\n')

          const newMessage: Message = {
            id: Date.now().toString(),
            content: userContent,
            role: 'user',
            timestamp: Date.now()
          }
          this.messages.push(newMessage)

          // 调用普通接口（非流式）
          const response = await api.sendMessage2(chatRequest)
          const aiContent = JSON.stringify(response) // 根据后端实际响应结构调整
          console.log("2222222", response);
          console.log("aiContent", aiContent);


          this.messages.push({
            id: (Date.now() + 1).toString(),
            content: aiContent,
            role: 'assistant',
            timestamp: Date.now()
          })
        } catch (err) {
          const errorMessage = err instanceof Error ? err.message : '发送消息失败'
          this.error = errorMessage
          ElMessage.error(errorMessage)
        } finally {
          this.isLoading = false
        }
      } else if (chatRequest.isStream === 3) {
        try {
          this.isLoading = true

          // 创建用户消息
          const userContent = chatRequest.contents
            .map(content => content.content)
            .join('\n')

          const newMessage: Message = {
            id: Date.now().toString(),
            content: userContent,
            role: 'user',
            timestamp: Date.now()
          }
          this.messages.push(newMessage)

          // 调用普通接口（非流式）
          const response = await api.sendMessage3(chatRequest)
          const aiContent = JSON.stringify(response) // 根据后端实际响应结构调整

          this.formData = response || {}

          return response;



          // this.messages.push({
          //   id: (Date.now() + 1).toString(),
          //   content: aiContent,
          //   role: 'assistant',
          //   timestamp: Date.now()
          // })
        } catch (err) {
          const errorMessage = err instanceof Error ? err.message : '发送消息失败'
          this.error = errorMessage
          ElMessage.error(errorMessage)
        } finally {
          this.isLoading = false
        }

      }
    },

    async loadHistory(chatRequest: ChatRequest) {
      try {
        const response = await api.getHistory(chatRequest.userId)

        console.log("loadHistory", response);
        if (response) {
          response.forEach((item: any) => {
            if (item.roleType == "USER") {
              const newMessage: Message = {
                // id: item.id,
                content: item.contents[0].content,
                role: "user",
                timestamp: item.timestamp
              }
              this.messages.push(newMessage)
            } else if (item.roleType == "AI") {

              this.messages.push({
                id: (Date.now() + 1).toString(),
                content: item.contents[0].content,
                role: 'assistant',
                timestamp: item.timestamp
              })

            }

          })

        }
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : '加载历史记录失败'
        ElMessage.error(errorMessage)
      }
    },


    //获取建议搜索内容
    async getSuggestions(question: String) {

      const response = await api.getSuggestions(question)
      console.log("getSuggestions", response);
      return response

    },

    //清空历史记录
    clearHistory(chatRequest: ChatRequest) {
      this.messages = []
      // api.clearHistory(chatRequest.userId)
    },
    //清空历史记录
    clearHistory2(chatRequest: ChatRequest) {
      console.log("清空历史记录", chatRequest);
      this.messages = []
      api.clearHistory(chatRequest)
    }
  }
})